package cn.virens.common.boot.filter.autoconfig;

import cn.virens.common.boot.filter.FilterRegistrationBeanAware;
import cn.virens.common.boot.filter.exception.SimpleHandlerExceptionCustomizer;
import cn.virens.common.boot.filter.exception.SimpleHandlerExceptionFilter;
import cn.virens.common.boot.filter.exception.SimpleHandlerExceptionProperties;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

@AutoConfiguration
@EnableConfigurationProperties(SimpleHandlerExceptionProperties.class)
@ConditionalOnProperty(prefix = "virens.filter.exception", value = "enabled")
public class SimpleHandlerExceptionAutoConfig {

    @Bean(value = "simpleHandlerExceptionFilter")
    @ConditionalOnBean(value = FastJsonConfig.class)
    @ConditionalOnMissingBean(name = "simpleHandlerExceptionFilter")
    public FilterRegistrationBean<SimpleHandlerExceptionFilter> simpleHandlerExceptionFilter(ObjectProvider<SimpleHandlerExceptionCustomizer> exceptionCustomizers, //
                                                                                             SimpleHandlerExceptionProperties properties, //
                                                                                             FastJsonConfig fastJsonConfig //
    ) {
        SimpleHandlerExceptionFilter simpleHandlerExceptionFilter = new SimpleHandlerExceptionFilter(fastJsonConfig, properties);
        simpleHandlerExceptionFilter.addExceptionMessage(MaxUploadSizeExceededException.class, "文件大小超出限制");
        simpleHandlerExceptionFilter.addExceptionMessage(NoHandlerFoundException.class, "接口不存在");

        properties.pushBlackPatterns(simpleHandlerExceptionFilter::addBlackPatterns);
        properties.pushWhitePatterns(simpleHandlerExceptionFilter::addWhitePatterns);

        exceptionCustomizers.orderedStream().forEach(c -> c.customize(simpleHandlerExceptionFilter));

        // 拦截器注册对象Bean
        var registrationBean = new FilterRegistrationBeanAware<SimpleHandlerExceptionFilter>();
        registrationBean.setOrder(SimpleFilterOrdered.FILTER_EXCEPTION);
        registrationBean.setFilter(simpleHandlerExceptionFilter);
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }
}
